package org.halk.controller;

import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.halk.util.FileMonitorListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.yaml.snakeyaml.Yaml;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Map;

@RestController
@Slf4j
public class HelloController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Value("${halk.monitor.path}")
    private String monitorPath;
    @Value("${halk.xiaoming.sex}")
    private String sex;

    @GetMapping("/get")
    public String get() {
        Long increment = this.stringRedisTemplate.opsForValue().increment("halk:count", 1);
        log.info("redis increment {}", increment);
        return increment != null ? increment.toString() : "error";
    }

    @GetMapping("/hello")
    public String hello() {
        log.info("hello");
        String name = "default";
        String age = "default";
        Yaml yaml = new Yaml();
        try (FileInputStream inputStream = new FileInputStream(monitorPath + "application.yml")) {
            Map<String, Object> data = yaml.load(inputStream);
            // 获取嵌套的配置项
            Map<String, Object> halkConfig = (Map<String, Object>) data.get("halk");
            if (halkConfig != null) {
                Map<String, Object> xiaomingConfig = (Map<String, Object>) halkConfig.get("xiaoming");
                if (xiaomingConfig != null) {
                    name = String.valueOf(xiaomingConfig.get("name"));
                    age = String.valueOf(xiaomingConfig.get("age"));
                    log.info("配置文件重新加载! 时间：{} age: {}", DateUtil.format(LocalDateTime.now(), "yyyy-MM-dd HH:mm:ss"), age);
                } else {
                    log.error("配置文件中未找到 halk.xiaoming 配置项！");
                }
            } else {
                log.error("配置文件中未找到 halk 配置项！");
            }
        } catch (IOException e) {
            log.error("读取配置文件时发生错误！位置：", e);
        }

        return "hello world : " + name + " " + age + " " + sex;
    }



}
